package io.github.eiot.json.deserializer;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.deser.BeanDeserializerBase;
import com.fasterxml.jackson.databind.deser.ContextualDeserializer;
import com.fasterxml.jackson.databind.introspect.AnnotatedMember;
import io.github.eiot.annotation.FrameField;
import io.github.eiot.annotation.FrameFieldLoop;
import io.github.eiot.codec.NumberUnit;

import java.io.IOException;

/**
 * created by wang007 on 2025/9/27
 */
public abstract class AbstractNumberUnitDeserializer<T extends NumberUnit> extends JsonDeserializer<T> implements ContextualDeserializer {

    protected final FrameField frameField;

    protected AbstractNumberUnitDeserializer(FrameField frameField) {
        this.frameField = frameField;
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, BeanProperty property) throws JsonMappingException {
        AnnotatedMember member = property.getMember();
        FrameField frameField = member.getAnnotation(FrameField.class);
        if (frameField != null) {
            return createSelf(frameField);
        }
        FrameFieldLoop loop = member.getAnnotation(FrameFieldLoop.class);
        if (loop != null) {
            return createSelf(loop.frameField());
        }
        throw JsonMappingException.from(ctxt, property.getName() + " not found FrameField or FrameFieldLoop annotation");
    }

    protected abstract JsonDeserializer<?> createSelf(FrameField frameField);
}
